package com.sq.universe.base.utils;

import com.sq.universe.base.constants.BaseConstants;
import com.sq.universe.base.entity.BusinessException;
import com.sq.universe.system.entity.UserEntity;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public class AuthUtils {

    /**
     * 获取当前用户
     * @return
     */
    public static UserEntity getCurrentUser(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String id = WebUtils.toHttp(request).getHeader("X-Token");
        if(id == null){
            id = request.getParameter("X-Token");
        }
        if( id != null){
            UserEntity userEntity = (UserEntity) SecurityUtils.getSubject().getSession().getAttribute(BaseConstants.CURRENT_USER);
            if(userEntity == null || userEntity.getUserId() == null){
                throw new BusinessException("401","用户信息获取失败");
            }
            return userEntity;
        }else{
            throw new BusinessException("401","用户信息获取失败");
        }

    }

    /**
     * 获取当前用户
     * @return
     */
    public static Map<String ,String> getCurrnetAuth(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String id = WebUtils.toHttp(request).getHeader("X-Token");
        if(id == null){
            id = request.getParameter("X-Token");
        }
        if( id != null){
            Map menuMap = (Map) SecurityUtils.getSubject().getSession().getAttribute(BaseConstants.CURRENT_USER_AUTH);
            return menuMap;
        }else{
            throw new BusinessException("401","用户信息获取失败");
        }
    }
}
